package poli.tidia.mobile.proxy;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import poli.tidia.mobile.model.Announcement;
import poli.tidia.mobile.model.AnnouncementMenuItem;
import poli.tidia.mobile.model.Site;

public class AnnouncementsProxy {
	public List<AnnouncementMenuItem> getLastAnnouncements(Site site)
	{
		List<AnnouncementMenuItem> result = new ArrayList<AnnouncementMenuItem>();
        RestClient client;
        try {
        	String response;
        	Document doc;
        	
        	if(site.getAnnouncementsPortletUrl().equals(""))
        	{
        		client = RestClient.getInstance(site.getAnnouncementsUrl());
				client.Execute(RestClient.RequestMethod.GET);
				response = client.getResponse();
		        doc = Jsoup.parse(response);
		        site.setAnnouncementsPortletUrl(doc.select(".portletMainWrap").first().child(0).attr("src"));
        	}
        	
        	client = RestClient.getInstance(site.getAnnouncementsPortletUrl());
        	client.Execute(RestClient.RequestMethod.GET);
        	response = client.getResponse();
        	doc = Jsoup.parse(response);
        	Elements announcementsDOM = doc.select("td[headers=subject]");
        	for (Element element : announcementsDOM) {
				Element linkElement = element.select("a").first();
				result.add(new AnnouncementMenuItem(linkElement.text(), linkElement.attr("href").toString()));
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        return result;
	}
	
	public Announcement getAnnouncement(String announcementUrl)
	{
		Announcement result = null;
		
		try {
			RestClient client = RestClient.getInstance(announcementUrl);
			client.Execute(RestClient.RequestMethod.GET);
        	String response = client.getResponse();
        	Document doc = Jsoup.parse(response);
        	
        	String subject = doc.select(".itemSummary").select("td").get(0).text();
        	String author = doc.select(".itemSummary").select("td").get(1).text();
        	String createdDateString = doc.select(".itemSummary").select("td").get(2).text().split(" ")[0];
        	SimpleDateFormat curFormater = new SimpleDateFormat("dd/MM/yyyy"); 
        	Date created = curFormater.parse(createdDateString); 
        	
        	String message = doc.select("p").first().text();
        	result = new Announcement(subject, author, created, message);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return result;
	}
}
